package com.crm.services;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.model.jdao.IProductDAO;
import com.crm.model.jdao.IQuotationDetailDAO;
import com.crm.model.jdao.ISalesOpportunityDAO;
import com.crm.model.jdao.ISalesTrackingLogDAO;
import com.crm.model.jdao.IShowsettingSalesOpportunityDAO;
import com.crm.model.pojo.Customer;
import com.crm.model.pojo.Dictionary;
import com.crm.model.pojo.Product;
import com.crm.model.pojo.QuotationDetail;
import com.crm.model.pojo.QuotationRecord;
import com.crm.model.pojo.SalesOpportunity;

/**
 * 报价明细
 * @author 飞鱼
 *
 */
@Service
public class QuotationDetailServices {

	@Autowired
	private IQuotationDetailDAO qdDAO;
	@Autowired
	private QuotationDetailServices qds;
	@Autowired
	private ISalesOpportunityDAO salDAO;
	@Autowired
	private SalesOpportunityServices ss;
	@Autowired
	private DictionaryServices ds;
	@Autowired
	private UserServices us;	
	@Autowired
	private IProductDAO prdDAO;
	@Autowired
	private CompetitorServices cs;
	private static int count=0;
	/**
	 * 报价记录新增
	 * @param sale
	 * @return
	 */
	public int save(QuotationDetail newsale) {
		qdDAO.save(newsale);		
		return 1;		
	}
	/**
	 * 
	 * @param pageNumber  从那天开始显示
	 * @param pageContent 显示的记录条数
	 * @return
	 */
/*	public List<QuotationDetail> queryByAll(int pageNumber,int pageContent,String[] DId){
		Sort sort=Sort.by(Direction.DESC, "qdDetailId");
		Pageable pageable =PageRequest.of(pageNumber,pageContent,sort);	
		//查询条件构造
		 Specification<QuotationDetail> spec=new Specification<QuotationDetail>(){

			@Override
			public Predicate toPredicate(Root<QuotationDetail> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				//Path<Object> state=root.get("state");
				List<Predicate> list=new ArrayList<>();
				System.out.println("ss的DId:"+DId);
					if(DId.length==0) {
						list.add(cb.equal(root.get("state").as(Integer.class), 1));
					}
					int i=0;
					for (String str : DId) {
						System.out.println("str:"+str);
						if("全部数据".equals(str)) {
							 list.add(cb.equal(root.get("state").as(Integer.class), 1));	
						}
						if("客户名称".equals(str)) {
							System.out.println("触发了模糊客户名称数据筛选");	
							//cb.countDistinct(root.join("customer").get("custName")));
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.join("customer").get("custName").as(String.class),"%"+DId[i+2]+"%"));									
							}else {
								list.add(cb.like(root.join("customer").get("custName").as(String.class),"%"+DId[i+1]+"%"));
							    query.groupBy(root.get("customer").as(Customer.class));
							}

						}
						if("产品名".equals(str)) {
							System.out.println("触发了模糊方案主题数据筛选");	
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.get("qdProduct").as(String.class),"%"+DId[i+2]+"%"));								
							}else {
								list.add(cb.like(root.get("qdProduct").as(String.class),"%"+DId[i+1]+"%"));
							}

							//cb.countDistinct(root.join("customer").get("custName")));
							
						}
						if("负责人".equals(str)) {
							System.out.println("触发了模糊负责人数据筛选");	
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.join("salesOpportunity").get("salTheme").as(String.class),"%"+DId[i+2]+"%"));									
							}else {
								list.add(cb.like(root.join("salesOpportunity").get("salTheme").as(String.class),"%"+DId[i+1]+"%"));	
								query.groupBy(root.get("salesOpportunity").as(SalesOpportunity.class));
							}						
													
						}	
						i++;
					}

		        Predicate[] p = new Predicate[list.size()];
		        System.out.println("-----------------------------------------");
			    query.where(list.toArray(p));
				return query.getRestriction();
			}
			 
		 };
		Page<QuotationDetail> page =qdDAO.findAll(spec,pageable);		
		System.out.println("总记录数："+page.getTotalElements());
		count=(int) page.getTotalElements();
		List<QuotationDetail> list=page.getContent();
		return list;		
	}*/
	
	/**
	 *将list的数据转换成JsonArray的数据
	 * @return
	 */
/*	public JSONArray ListTransJSONArray(int pageNumber,int pageContent,String[] DId) {
		JSONArray array =new JSONArray();
		List<QuotationDetail> list=qds.queryByAll(pageNumber,pageContent,DId);
		for (QuotationDetail Competitor : list) {
		//System.out.println("Competitor:"+Competitor);
			JSONObject obj = new JSONObject();		
			array.add(toJSONObject1( obj,Competitor));
	}
		return array;
	}*/
	
	/**
	 * 统计对象个数
	 * @return
	 */
	public int queryByCount() {
		return count;
		
	}
	/**
	 *将list的数据转换成JsonArray的数据
	 * @return
	 */
	public JSONArray ListTransJSONArray(Integer id) {
		JSONArray array =new JSONArray();
		//List<QuotationDetail> list=qds.queryByAll(pageNumber,pageContent,DId);
		QuotationRecord quotationRecord=new QuotationRecord();
		quotationRecord.setQdRecordId(id);
		List<QuotationDetail> list=qdDAO.findByQuotationRecord(quotationRecord);
		for (QuotationDetail Competitor : list) {
		//System.out.println("Competitor:"+Competitor);
			JSONObject obj = new JSONObject();		
			array.add(toJSONObject1( obj,Competitor));
	}
		return array;
	}
	
	/**
	 * 是用于转换订单明细的时候
	 * @param id
	 * @return
	 */
	public List<QuotationDetail> findByQuotationRecord(Integer id){
		QuotationRecord quotationRecord=new QuotationRecord();
		quotationRecord.setQdRecordId(id);	
		return qdDAO.findByQuotationRecord(quotationRecord);
		
	}
	
	
	public void save(List<Map<String,String>> limap,Integer id) {
		for (Map<String, String> map : limap) {
			QuotationDetail qd=new QuotationDetail();
			QuotationRecord qr=new QuotationRecord();
			qr.setQdRecordId(id);
			qd.setDiscount(new BigDecimal(String.valueOf(map.get("discount"))));
			qd.setMoney(new BigDecimal(String.valueOf(map.get("money"))));
			qd.setQdNotes(String.valueOf(map.get("qdNotes")));
			qd.setQdNumber(Integer.parseInt(String.valueOf(map.get("qdNumber"))));
			qd.setQdPrice(new BigDecimal(String.valueOf(map.get("qdPrice"))));
			qd.setQdProduct(Integer.parseInt(String.valueOf(map.get("pId"))));
			qd.setQdTransactionPrice(new BigDecimal(String.valueOf(map.get("qdTransactionPrice"))));
			qd.setQdUnit(String.valueOf(map.get("qdUnit")));
			qd.setQuotationRecord(qr);
			if(!"".equals(map.get("qdDetailId"))) {
				qd.setQdDetailId(Integer.parseInt(String.valueOf(map.get("qdDetailId"))));				
			}
			qd.setState(1);
			qdDAO.save(qd);
		}
	}
	/**
	 * 报价记录转JSONObject
	 * @param obj
	 * @param Competitor
	 * @return
	 */
	public JSONObject toJSONObject1(JSONObject obj,QuotationDetail Competitor) {
		/*obj.put("salId", Competitor.getSalId());
		obj.put("salTheme", Competitor.getSalTheme());
		obj.put("custName", Competitor.getCustomer().getCustName());
		String starURL=ss.starURL(Competitor.getStarStandard());
		obj.put("starStandard",starURL);
		obj.put("salType", ds.findByDictId(Competitor.getSalType()));
		if(Competitor.getSotlDate()!=null) {
			obj.put("sotlDate",Competitor.getSotlDate().toString());			
		}				
		obj.put("sotlMoney", Competitor.getSotlMoney());
		obj.put("custDemand", Competitor.getCustDemand());
		obj.put("salStageStop", Competitor.getSalStageStop()+"天");
		obj.put("salState",Competitor.getSalState());
		obj.put("salSource", ds.findByDictId(Competitor.getSalSource()));
		obj.put("sotlId", ss.findByUserName(Competitor.getSotlId()));
		obj.put("salState", ds.findByDictId(Competitor.getSalState())+"");		
		obj.put("salPossibility", ds.findByDictId(Competitor.getSalPossibility()));
		obj.put("salUpdatetime", Competitor.getSalUpdatetime().toString());
		//obj.put("", value);*/
		Product p=prdDAO.findByPId(Competitor.getQdProduct());
		obj.put("qdDetailId", Competitor.getQdDetailId());
		obj.put("qdProduct", p.getPName());
		obj.put("pId", prdDAO.findByPId(Competitor.getQdProduct()).getPId());
		obj.put("qdNumber", Competitor.getQdNumber());
		obj.put("qdPrice", Competitor.getQdPrice());	
		obj.put("qdUnit",ds.findByDictId(p.getPUnit()));
		obj.put("qdTransactionPrice",Competitor.getQdTransactionPrice());
		obj.put("qdNotes",Competitor.getQdNotes());	
		obj.put("discount", Competitor.getDiscount());
		obj.put("money", Competitor.getMoney());		
		obj.put("quotationRecord", Competitor.getQuotationRecord().getQdRecordId());
		return obj;
	}

}
